package @@proxiesPackage@@;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.*;
import com.google.gwt.json.client.*;

public class ProxyHelper {
    private static final int STATUS_CODE_OK = 200;

    public static Request sendRequest(String serviceUrl, String postData, RequestCallback callback) {
        GWT.log(postData + " to " + serviceUrl, null);

        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, serviceUrl);

        Request request = null;
        try {
            request = builder.sendRequest(postData, callback);
        } catch (Throwable exception) {
            callback.onError(request, exception);
        }

        return request;
    }

    public static JSONValue parseResponse(Response response) {
        if (response.getStatusCode() != STATUS_CODE_OK) {
            String message = response.getStatusCode() + " " + response.getStatusText();
            throw new RuntimeException(message);
        }

        String responseText = response.getText();
        if (responseText == null || responseText.length() == 0) {
            String message = "Server returned empty response.";
            throw new RuntimeException(message);
        }

        GWT.log("responseText = " + responseText, null);

        JSONObject responseObject;
        try {
            JSONValue value = JSONParser.parse(responseText);

            responseObject = value.isObject();
            if (responseObject == null) {
                throw new JSONException("expected JSONObject, actual " + value.toString());
            }

        } catch (Throwable exception) {
            String message = "Could not parse the response.";
            throw new JSONException(message, exception);
        }

        JSONValue errorValue = responseObject.get("error");
        if (errorValue != null && errorValue.isString() != null) {
            throw new RuntimeException(errorValue.isString().stringValue());
        }

        return responseObject.get("result");
    }
}
